<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属题库" prop="bankId">
        <el-select v-model="queryParams.bankId" placeholder="请选择所属题库" clearable size="small">
          <el-option v-for="bank in bankList"
                     :key="bank.id" :label="bank.name" :value="parseInt(bank.id)"/>
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="父ID" prop="parentQuestionId">-->
      <!--        <el-input v-model="queryParams.parentQuestionId" placeholder="请输入父ID" clearable @keyup.enter.native="handleQuery"/>-->
      <!--      </el-form-item>-->
      <el-form-item label="试题类型" prop="questionType">
        <el-select v-model="queryParams.questionType" placeholder="请选择试题类型" clearable size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.QUESTION_TYPE)"
                     :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="难度等级" prop="questionLevel">
        <el-select v-model="queryParams.questionLevel" placeholder="请选择难度等级" clearable size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.QUESTION_LEVEL)"
                     :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['question:question:create']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   :loading="exportLoading"
                   v-hasPermi="['question:question:export']">导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list">
<!--      <el-table-column label="试题id" align="center" prop="id"/>-->
      <el-table-column label="所属题库" align="center" prop="bankId">
        <template v-slot="scope">
          <el-tag>{{getBankName(scope.row.bankId)}}</el-tag>
        </template>
      </el-table-column>
<!--      <el-table-column label="父ID" align="center" prop="parentQuestionId"/>-->
      <el-table-column label="试题内容" align="center" prop="questionContent">
        <template v-slot="scope">
          <div v-html="scope.row.questionContent"></div>
        </template>
      </el-table-column>
      <el-table-column label="试题类型" align="center" prop="questionType">
        <template v-slot="scope">
          <dict-tag :type="DICT_TYPE.QUESTION_TYPE" :value="scope.row.questionType"/>
        </template>
      </el-table-column>
      <el-table-column label="难度等级" align="center" prop="questionLevel">
        <template v-slot="scope">
          <dict-tag :type="DICT_TYPE.QUESTION_LEVEL" :value="scope.row.questionLevel"/>
        </template>
      </el-table-column>
      <el-table-column label="整题解析" align="center" prop="standardAnalysis">
        <template v-slot="scope">
          <div v-html="scope.row.standardAnalysis"></div>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['question:question:update']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['question:question:delete']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" v-dialogDrag append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属题库" prop="bankId">
          <el-select v-model="form.bankId" placeholder="请选择所属题库">
            <el-option v-for="bank in bankList"
                       :key="bank.id" :label="bank.name" :value="parseInt(bank.id)"/>
          </el-select>
        </el-form-item>
        <el-form-item label="试题类型" prop="questionType">
          <el-select v-model="form.questionType" placeholder="请选择试题类型" @change="onQuestionTypeChange">
            <el-option v-for="dict in this.getDictDatas(DICT_TYPE.QUESTION_TYPE)"
                       :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"/>
          </el-select>
        </el-form-item>
        <el-form-item label="难度等级" prop="questionLevel">
          <el-select v-model="form.questionLevel" placeholder="请选择难度等级">
            <el-option v-for="dict in this.getDictDatas(DICT_TYPE.QUESTION_LEVEL)"
                       :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"/>
          </el-select>
        </el-form-item>
        <!--        <el-form-item label="父ID" prop="parentQuestionId">-->
        <!--          <el-input v-model="form.parentQuestionId" placeholder="请输入父ID" />-->
        <!--        </el-form-item>-->
        <el-form-item label="试题内容" prop="questionContent">
          <editor v-model="form.questionContent" :min-height="192"/>
        </el-form-item>

        <el-form-item label="整题解析" prop="standardAnalysis">
          <editor v-model="form.standardAnalysis" :min-height="192"/>
        </el-form-item>

        <el-button class="itemButton" type="primary" :disabled="form.questionType == 3 && questionItemList.length == 2" plain @click="addQuestionItem" v-if="form.questionType == 1 || form.questionType == 2 || form.questionType == 3 || form.questionType == 5">添加选项</el-button>
        <el-table :data="questionItemList" v-if="form.questionType == 1 || form.questionType == 2 || form.questionType == 3">
          <el-table-column label="是否答案" align="center" prop="isAnswer">
            <template v-slot="scope">
              <el-checkbox v-model="scope.row.isAnswer" label="答案" @change="(value)=>onItemIsAnswerChange(value, scope.row.id)"></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column label="选项图片" align="center" prop="itemImg" width="380">
            <template v-slot="scope">
              <div>
                <el-upload
                  class="upload-demo"
                  accept=".jpg, .png"
                  :on-remove="handleRemove"
                  :before-remove="beforeRemove"
                  :headers="upload.headers" :action="upload.url" :data="upload.data"
                  :limit="1"
                  :on-exceed="handleExceed"
                  :on-success="(response, file, fileList)=>handleFileSuccess(scope.row, response, file, fileList)"
                  list-type="picture-card"
                  :file-list="scope.row.fileList">
                  <i class="el-icon-plus"></i>
                </el-upload>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="选项内容" align="center" prop="itemContent" width="200">
            <template v-slot="scope">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入选项内容"
                v-model="scope.row.itemContent">
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="选项解析" align="center" prop="itemAnalysis" width="200">
            <template v-slot="scope">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入选项解析"
                v-model="scope.row.itemAnalysis">
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template v-slot="scope">
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteItem(scope.row.id)"
                         v-hasPermi="['question:question:delete']">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-table :data="questionItemList" v-if="form.questionType == 5">
          <el-table-column label="选项内容" align="center" prop="itemContent" width="800">
            <template v-slot="scope">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="填空题支持多个近似答案用||隔开，如：10||十，学员填写`10`或者`十`都判为正确"
                v-model="scope.row.itemContent">
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template v-slot="scope">
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteItem(scope.row.id)"
                         v-hasPermi="['question:question:delete']">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-form-item prop="itemOrder" v-if="form.questionType == 5">
          <el-checkbox v-model="form.itemOrder" label="严格按序作答"></el-checkbox>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {create, update, deleteQuestion, get, getPage, exportExcel} from "@/api/question/question";
import {getBankList} from "@/api/question/bank";
import Editor from '@/components/Editor';
import {getAccessToken} from "@/utils/auth";

export default {
  name: "",
  components: {
    Editor,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 试题信息列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        bankId: null,
        parentQuestionId: null,
        questionContent: null,
        questionType: null,
        questionLevel: null,
        standardAnalysis: null,
      },
      // 表单参数
      form: {
        questionType: 4
      },
      // 表单校验
      rules: {
        bankId: [{required: true, message: "所属题库不能为空", trigger: "blur"}],
        questionType: [{required: true, message: "试题类型不能为空", trigger: "change"}],
        questionLevel: [{required: true, message: "难度等级不能为空", trigger: "change"}],
        questionContent: [{required: true, message: "试题内容不能为空", trigger: "blur"}],
        standardAnalysis: [{required: true, message: "整题解析不能为空", trigger: "blur"}]
      },
      bankList: [],
      questionItemList: [],
      // 用户导入参数
      upload: {
        open: false, // 是否显示弹出层
        title: "", // 弹出层标题
        isUploading: false, // 是否禁用上传
        url: process.env.VUE_APP_BASE_API + "/admin-api/infra/file/upload", // 请求地址
        headers: {Authorization: "Bearer " + getAccessToken()}, // 设置上传的请求头部
        data: {} // 上传的额外数据，用于文件名
      },
    };
  },
  created() {
    this.getList();
    this.getAllBankList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getPage(this.queryParams).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    getBankName(bankId) {
      let bankName = ''
      this.bankList.forEach(b=> {
        if (b.id == bankId) {
          bankName = b.name
        }
      })
      return bankName;
    },
    onQuestionTypeChange(v) {
      this.questionItemList = [];
      switch (this.form.questionType) {
        case 1:
        case 2:
          this.questionItemList= [
            {
              id: Math.random() * 100,
              isAnswer: true,
              itemContent: '',
              itemAnalysis: '',
              itemImg: '',
              dialogImageUrl: '',
              dialogVisible: false,
              disabled: false
            },
            {
              id: Math.random() * 100,
              isAnswer: false,
              itemContent: '',
              itemAnalysis: '',
              itemImg: '',
              dialogImageUrl: '',
              dialogVisible: false,
              disabled: false
            },
            {
              id: Math.random() * 100,
              isAnswer: false,
              itemContent: '',
              itemAnalysis: '',
              itemImg: '',
              dialogImageUrl: '',
              dialogVisible: false,
              disabled: false
            },
          ]
          break;
        case 5:
          this.questionItemList= [
            {
              id: Math.random() * 100,
              isAnswer: true,
              itemContent: '',
              itemAnalysis: '',
              itemImg: '',
              dialogImageUrl: '',
              dialogVisible: false,
              disabled: false
            },
            {
              id: Math.random() * 100,
              isAnswer: true,
              itemContent: '',
              itemAnalysis: '',
              itemImg: '',
              dialogImageUrl: '',
              dialogVisible: false,
              disabled: false
            }
          ]
          break;
        case 3:
          this.questionItemList= [
            {
              id: Math.random() * 100,
              isAnswer: true,
              itemContent: '正确',
              itemAnalysis: '',
              itemImg: '',
              dialogImageUrl: '',
              dialogVisible: false,
              disabled: false
            },
            {
              id: Math.random() * 100,
              isAnswer: false,
              itemContent: '错误',
              itemAnalysis: '',
              itemImg: '',
              dialogImageUrl: '',
              dialogVisible: false,
              disabled: false
            },
          ]
          break;
      }
      console.log(v)
      console.log(this.form)
    },
    /**
     * 查询题库列表
     */
    getAllBankList() {
      getBankList().then(response => {
        this.bankList = response.data
      })
    },
    /**
     * 添加选项
     */
    addQuestionItem() {
      this.questionItemList.push({
        id: Math.random() * 100,
        isAnswer: false,
        itemContent: '',
        itemAnalysis: '',
        itemImg: '',
        dialogImageUrl: '',
        dialogVisible: false,
        disabled: false
      })
    },
    /**
     * 是否答案
     */
    onItemIsAnswerChange(v, itemId) {
      if (v) {
        switch (this.form.questionType) {
          case 1:
          case 3:
            this.questionItemList.forEach(i=> {
              if (i.id != itemId) {
                i.isAnswer = false
              }
            })
            break;
          case 2:
            break;
        }

      }
    },
    /**
     * 删除选项
     */
    handleDeleteItem(id) {
      this.questionItemList = this.questionItemList.filter(i => {
        return i.id != id
      })
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    // handlePreview(file) {
    //   console.log(file);
    // },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    /** 文件上传成功处理 */
    handleFileSuccess(row, response, file, fileList) {
      row.itemImg = response.data
      console.log(this.questionItemList)
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        bankId: undefined,
        parentQuestionId: undefined,
        questionContent: undefined,
        questionType: undefined,
        questionLevel: undefined,
        standardAnalysis: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加试题信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      get(id).then(response => {
        this.form = response.data;
        this.questionItemList = response.data.questionItemList
        this.open = true;
        this.title = "修改试题信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        this.form.questionItemList = this.questionItemList
        // 修改的提交
        if (this.form.id != null) {
          update(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        create(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除试题信息编号为"' + id + '"的数据项?').then(function () {
        return deleteQuestion(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal.confirm('是否确认导出所有试题信息数据项?').then(() => {
        this.exportLoading = true;
        return exportExcel(params);
      }).then(response => {
        this.$download.excel(response, '试题信息.xls');
        this.exportLoading = false;
      }).catch(() => {
      });
    }
  }
};
</script>

<style>
  .itemButton {
    margin-bottom: 20px;
  }
</style>
